package net.oschina.dajiangnan.wx.process.mp.tools;

import java.util.TimerTask;

import net.oschina.dajiangnan.wx.util.HttpTookit;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import net.oschina.dajiangnan.wx.constants.Config;
import net.oschina.dajiangnan.wx.process.mp.json.AccessToken;
import net.oschina.dajiangnan.wx.process.mp.json.Ips;
import net.oschina.dajiangnan.wx.process.mp.json.JsApiResult;
import net.oschina.dajiangnan.wx.process.mp.json.Result;

public class TickRefreshTask extends TimerTask {

	private static Logger logger = Logger.getLogger(TickRefreshTask.class);

	private static final String access_tocket_urlPrefix = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
	private static final String jsapi_ticket_urlPrefix = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?";
	private static final String get_weixin_server_ip_urlPrefix = "https://api.weixin.qq.com/cgi-bin/getcallbackip?";

	private String access_token = "";
	private String jsapi_ticket = "";
	private Ips ips = null;
	
	public String getAccessToken() {
		if (access_token.equals("") || jsapi_ticket.equals("")) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			return getAccessToken();
		}
		synchronized (TickRefreshTask.class) {
			return access_token;
		}
	}

	public String getJsApiTicket() {
		if (access_token.equals("") || jsapi_ticket.equals("")) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			return getJsApiTicket();
		}
		synchronized (TickRefreshTask.class) {
			return jsapi_ticket;
		}
	}

	public Ips getIps(){
	    if(ips == null){
	        try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            return getIps();
	    }
	    synchronized (TickRefreshTask.class) {
            return ips;
        }
	}
	
	
	
	
	
	
	
	@Override
	public void run() {
		try {
			synchronized (TickRefreshTask.class) {
				String access_token = getAccessToken_();
				if (access_token != null) {
				    synchronized (TickRefreshTask.class) {
				        this.access_token = access_token;
				    }
				    Ips ips = getIPs();
				    if(ips != null){
				        synchronized (TickRefreshTask.class) {
	                        this.ips = ips;
	                    }
				    }
					String jsapi_ticket = getJsApiTicket_();
					if (jsapi_ticket != null) {
						synchronized (TickRefreshTask.class) {
							this.jsapi_ticket = jsapi_ticket;
						}
					}
				}
			}
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	private String getAccessToken_() {
		String url = access_tocket_urlPrefix + "&appid=" + Config.appid
				+ "&secret=" + Config.appSecret;
		String respContent;
		try {
			respContent = new HttpTookit().doGet(url, null);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		AccessToken accessToken = JSON.toJavaObject(
				JSON.parseObject(respContent), AccessToken.class);
		if (accessToken.getErrcode() == null) {
			logger.debug("获取 accessToken 成功 ，  " + accessToken);
			return accessToken.getAccess_token();
		} else {
			Result result = JSON.toJavaObject(JSON.parseObject(respContent),
					Result.class);
			logger.debug("获取 accessToken 失败 ， result = " + result);
			return null;
		}
	}

	private String getJsApiTicket_() {
		String url = jsapi_ticket_urlPrefix + "access_token=" + access_token
				+ "&type=jsapi";
		String respContent;
		try {
			respContent = new HttpTookit().doGet(url, null);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		JsApiResult jsApiResult = JSON.toJavaObject(
				JSON.parseObject(respContent), JsApiResult.class);
		if (jsApiResult.getErrcode().equals("0")) {
			logger.debug("获取 jsApiResult 成功  ,  " + jsApiResult);
			return jsApiResult.getTicket();
		} else {
			logger.debug("获取 jsApiResult 失败  , respContent = " + respContent
					+ " url = " + url);
			return null;
		}
	}

	private Ips getIPs() {
		String url = get_weixin_server_ip_urlPrefix + "access_token="+ access_token;
		
		String respContent = null;
		try {
			respContent = new HttpTookit().doGet(url, null);
			Ips ips =  JSON.toJavaObject(JSON.parseObject(respContent),Ips.class);
			logger.debug("获取信任IP成功,共"+ips.getIp_list().length+"个");
			return ips;
		} catch (Exception e) {
		    logger.debug("获取信任IP失败,respContent = " + respContent);
			e.printStackTrace();
			return null;
		}
		
	}
}
